<?php

class Friendsinviter_IndexController extends Core_Controller_Action_Standard
{

  public function init()
  {
    $ajaxContext = $this->_helper->getHelper('AjaxContext');
    $ajaxContext
      ->addActionContext('inviteresend', 'json')
      ->addActionContext('invitedelete', 'json')
      ->addActionContext('findfriends', 'json')
      ->addActionContext('getcontacts', 'json')
      ->addActionContext('hideteaser', 'json')
      ->addActionContext('notifyerror', 'json')
      ->initContext();
  }

  
  public function indexAction()
  {
    
    $api = Engine_Api::_()->getApi('core', 'friendsinviter');
    
    $api->cacheConfig();
    
    $settings = Engine_Api::_()->getApi('settings', 'core');
    if ($settings->getSetting('user.signup.inviteonly') == 1)
    {
      $this->_helper->requireAdmin();
    }

    $this->setupNavigation();
    

    // Make form
    $form = new Friendsinviter_Form_Invite();
    
    // Handling for users not logged in
    $this->_helper->requireUser()->isValid();

    $this->view->action = $this->view->url(array('module' => 'core', 'controller' => 'invite'), 'default', true);
    $this->view->nextStep = "";
    $this->view->show_skip_option = false;
    

    $this->view->login = $post_login = $this->getRequest()->getPost('user');
    $this->view->domain = $this->getRequest()->getPost('domain');
    $this->view->typed_domain = $this->getRequest()->getPost('domain_type');

    $this->view->provider = $this->getRequest()->getPost('provider', 'auto');
    $this->view->screen = $this->getRequest()->getPost('screen', 'webcontacts');
    $this->view->find_friends = 0;

    $this->view->captcha_id = '';
    $this->view->captcha_input = '';
    $this->view->render_captcha = Engine_Api::_()->getApi('settings', 'core')->core_spam_invite;
    
    // TOP/AVAILABLE DOMAINS, SERVICES
    list($this->view->domains, $this->view->services) = $api->fi_get_top_services();    

    $task = $this->getRequest()->getPost('task','');
    $is_error = 0;

    $this->view->invite_message = $this->getRequest()->getPost('invite_message', Zend_Registry::get('Zend_Translate')->_($settings->getSetting('invite.message', '')));

    if (Engine_Api::_()->getApi('settings', 'core')->core_spam_invite) {
    
      if($task == '') {
        $this->getSession('friendsinviter')->captcha_passed = false;
      }
  
      if ( $this->getRequest()->isPost() && !$this->getSession('friendsinviter')->captcha_passed  ) {
        
        if($form->isValid($this->getRequest()->getPost())) {
          $this->getSession('friendsinviter')->captcha_passed = true;
        } else {
          $is_error = 1;
          $this->view->error_message  = 100010152;
          $this->view->invite_emails = $this->getRequest()->getPost('invite_emails', array());
        }
        
      }
      
    }


    
    // TBD: check captcha
    if ( $this->getRequest()->isPost() && ($is_error == 0)) {

      if($task == "doinvitefriendsemail") {
        $email = $this->getRequest()->getPost('email', '');
        $email = explode('@', $email);
        $this->view->login = isset($email[0]) ? $email[0] : '';
        $this->view->typed_domain = isset($email[1]) ? $email[1] : '';
        $task = 'doinvitefriends';
      }
      

      $client = $_SERVER['REMOTE_ADDR'];

      if($task == "doinvitefriends") {

        $fi_result = $api->fi_fetch_contacts( array('viewer'            => Engine_Api::_()->user()->getViewer(),
                                                    'user'              => $this->view->login,
                                                    'pass'              => $this->getRequest()->getPost('pass', ''),
                                                    'domain'            => $this->view->domain,
                                                    'typed_domain'      => $this->view->typed_domain,
                                                    'provider'          => $this->view->provider,
                                                    'find_friends'      => $this->getRequest()->getPost('find_friends', 1),
                                                    'captcha_response'  => $this->getRequest()->getPost('captcha_response', null),
                                                    'session'           => $this->getRequest()->getPost('session', null),
                                                    'client'            => $client
                                                   )
                                            );

        if($fi_result['err'] && !$fi_result['captcha_required']) {
          $is_error = 1;
          $this->view->error_message  = $fi_result['err_msg'];
        }
        
        if($fi_result['captcha_required']) {
          $this->view->captcha_url = $fi_result['captcha_url'];
        }
        
        foreach($fi_result as $key => $value) {
          $this->view->$key = $value;
        }

      
      }

      if($task == "doinvitefriendsapi") {

        $fi_result = $api->fi_fetch_contacts_api( array('viewer'            => Engine_Api::_()->user()->getViewer(),
                                                    'user'              => $this->view->login,
                                                    'pass'              => $this->getRequest()->getPost('pass', ''),
                                                    'domain'            => $this->view->domain,
                                                    'typed_domain'      => $this->view->typed_domain,
                                                    'provider'          => $this->view->provider,
                                                    'find_friends'      => $this->getRequest()->getPost('find_friends', 1),
                                                    'captcha_response'  => $this->getRequest()->getPost('captcha_response', null),
                                                    'session'           => $this->getRequest()->getPost('session', null),
                                                    'apiresponse'       => $this->getRequest()->getPost('apiresponse', ''),
                                                    'client'            => $client
                                                   )
                                            );

        if($fi_result['err'] && !$fi_result['captcha_required']) {
          $is_error = 1;
          $this->view->error_message  = $fi_result['err_msg'];
        }
        
        if($fi_result['captcha_required']) {
          $this->view->captcha_url = $fi_result['captcha_url'];
        }
        
        foreach($fi_result as $key => $value) {
          $this->view->$key = $value;
        }

      
      }

      // SEND INVITATIONS
      if(($task == "doinvite") && ($is_error != 1)) {

        $fi_result = $api->fi_invite_contacts(  array('user'            => Engine_Api::_()->user()->getViewer(),
                                                      'invite_emails'   => $this->getRequest()->getPost('invite_emails', array()),
                                                      'invite_message'  => $this->getRequest()->getPost('invite_message', ''),
                                                      'session'         => $this->getRequest()->getPost('session', null),
                                                      'invite_ids'      => $this->getRequest()->getPost('invite_ids', null),
                                                      'social_contacts' => $this->getRequest()->getPost('social_contacts', 0),
                                                      'imported'        => $this->getRequest()->getPost('imported', null),
                                                     )
                                              
                                              );
        if($fi_result['err']) {
      
          if(!$fi_result['captcha_required']) {
            $is_error = 1;
            $this->view->error_message  = $fi_result['err_msg'];
          } else {
            $this->view->captcha_url = $fi_result['captcha_url'];
            $this->view->captcha_required = true;
            $this->view->captcha_task = 'challenge_response';
            $this->view->session = $fi_result['session'];
          }
      
        } else {
          $this->view->result = 100010137;
          $invite_emails = '';
          $this->view->invite_emails = $invite_emails;
          $this->getSession('friendsinviter')->captcha_passed = false;
        }
      
      }


      // CHALLENGE RESPONSE
      if(($task == "challenge_response") && ($is_error != 1)) {

        $fi_result = $api->fi_challenge_response(   array(
                                                          'captcha_response'  => $this->getRequest()->getPost('captcha_response', array()),
                                                          'session'           => $this->getRequest()->getPost('session', null),
                                                     )
                                                 
                                                 );
        if($fi_result['err']) {
      
          if(!$fi_result['captcha_required']) {
            $is_error = 1;
            $this->view->error_message = $fi_result['err_msg'];
          } else {
            $this->view->captcha_url = $fi_result['captcha_url'];
            $this->view->captcha_required = true;
            $this->view->captcha_task = 'challenge_response';
            $this->view->session = $fi_result['session'];
          }
      
        } else {
          
          $this->view->result = 100010137;
          $invite_emails = '';
          $this->view->invite_emails = $invite_emails;
          
        }
      
      }
      
      
      
      // CSV
      if(($task == "douploadcsv") && ($is_error != 1)) {
      
        $fi_result = $api->fi_uploadcsv( Engine_Api::_()->user()->getViewer(), $this->getRequest()->getPost('find_friends', 1) );
        if($fi_result['err']) {
          $is_error = 1;
          $this->view->error_message  = $fi_result['err_msg'];
        }
      
        foreach($fi_result as $key => $value) {
          $this->view->$key = $value;
        }
        
      }

    }


    if($this->getSession('friendsinviter')->captcha_passed) {
      $this->view->render_captcha = false;
    }
      
    
    $this->view->form = $form;
    
    

  

  }
  
  
  
  
  
  
  public function pendingAction()
  {

    if(!$this->_helper->requireUser->isValid()) {
      return;
    }

    $api = Engine_Api::_()->getApi('core', 'friendsinviter');
    
    $settings = Engine_Api::_()->getApi('settings', 'core');

    $this->setupNavigation();
    

    $table  = Engine_Api::_()->getDbTable('users', 'invite');

    $is_error = "";
    $result = "";
    
    $p = $this->getRequest()->get('p',1);
        

    $subselect_table = Engine_Api::_()->getDbTable('users', 'user');

    $subselect = $subselect_table->select()
                  ->from($subselect_table->info('name'), 'email');

    $table  = Engine_Api::_()->getDbTable('invites', 'invite');

    $select = $table->select()
                    ->setIntegrityCheck(false)
                    ->from($table->info('name'), array(
                        'COUNT(DISTINCT recipient) AS count'))
                    ->where('user_id = ?', Engine_Api::_()->user()->getViewer()->getIdentity())
                    ->where("recipient NOT IN (?)",$subselect);
                    
    $rows    = $table->fetchAll($select)->toArray();
    $invites_total = $rows[0]['count'];
    

    $invites_per_page = 50;
    $page_vars = $api->make_page($invites_total, $invites_per_page, $p);

    // @tbd - duplicate recipients - group by 
    $table  = Engine_Api::_()->getDbTable('invites', 'invite');
    $select = $table->select()
                    ->where('user_id = ?', Engine_Api::_()->user()->getViewer()->getIdentity())
                    ->where("recipient NOT IN (?)",$subselect)
                    ->order(array('timestamp DESC'))
                    ->limit($invites_per_page, $page_vars[0]);

    $invites = $table->fetchAll($select);
    
    $known_invites = array();
    $filtered_invites = array();
    foreach($invites as $key => $invite) {
      if(in_array($invite->recipient, $known_invites)) {
        continue;
      }
      $known_invites[] = $invite->recipient;
      $filtered_invites[] = $invite;
    }
    
    $invites = $filtered_invites;


    $this->view->invites = $invites;
    $this->view->invites_total = $invites_total;
    $this->view->p = $page_vars[1];
    $this->view->maxpage = $page_vars[2];
    $this->view->p_start = $page_vars[0]+1;
    $this->view->p_end = $page_vars[0]+count($invites);
    
    
  }




  public function statsAction()
  {

    if(!$this->_helper->requireUser->isValid()) {
      return;
    }

    $this->setupNavigation();

    $table = Engine_Api::_()->getDbTable('stats', 'friendsinviter');

    $select = $table->select()
                    ->where('user_id = ?', Engine_Api::_()->user()->getViewer()->getIdentity());
                    
    $invites = $table->fetchRow($select);

    $invites_sent = !empty($invites) ? $invites->invites_sent : 0;
    $invites_converted = !empty($invites) ? $invites->invites_converted : 0;
    
    // ASSIGN VARIABLES AND INCLUDE FOOTER
    $this->view->invites_sent = $invites_sent;
    $this->view->invites_converted = $invites_converted;
    
  }  


  public function unsubscribeAction()
  {

    $email = strtolower( $this->_getParam('email') );
    $task = $this->_getParam('task');
    $api = Engine_Api::_()->getApi('core', 'friendsinviter');
    
    if($task == 'unsubscribe') {
      
      if(!$api->is_email_address( $email ) ) {
        
        $this->view->error_message = 100010272;
        
      } else {
  
        $table  = Engine_Api::_()->getDbTable('unsubscribes', 'friendsinviter');
        $select = $table->select()
                        ->where('unsubscribe_user_email = ?', $email);
    
        $rows =  $table->fetchAll($select);
        
        
        if(count($rows) == 0) {
  
          $table->insert(array(
            'unsubscribe_user_email' => $email,
          ));
  
          // Cleanup possibly queued emails
          // @todo
          //$database->database_query("DELETE FROM se_semods_email_queue WHERE to_email = '$email' AND type = 10");
        }
        
        $email = '';
        $this->view->result = 100010273;
        $this->view->hide_unsubscribe_form = true;
      }
      
    }
    
  }  


  public function reflinkAction()
  {

    if(!$this->_helper->requireUser->isValid()) {
      return;
    }

    $this->setupNavigation();

    $viewer = Engine_Api::_()->user()->getViewer();
    //$referrer_id = $viewer->username;
    $referrer_id = $viewer->user_id;


    $invite_url     = "http://{$_SERVER['HTTP_HOST']}"
                    . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
                          'module'     => 'core',
                          'controller' => 'signup',
                          //'action' => null,
                          //'ref'     => $referrer_id), 'default');
                          ), 'default') . '?ref=' . $referrer_id;

    
    $this->view->reflink = $invite_url;

    
    
  }
  
  
  public function getNavigation() {

    $links = array( 
                array(
                      'label'      => 'Invite Friends',
                      'route'      => 'invite',
                      'action'     => 'index',
                      'controller' => 'index',
                      'module'     => 'friendsinviter'
                    ),
                array(
                      'label'      => 'Pending Invites',
                      'route'      => 'friendsinviter_pending',
                      'action'     => 'pending',
                      'controller' => 'index',
                      'module'     => 'friendsinviter'
                     ),
                array(
                      'label'      => 'Statistics',
                      'route'      => 'friendsinviter_stats',
                      'action'     => 'stats',
                      'controller' => 'index',
                      'module'     => 'friendsinviter'
                     ),
                array(
                      'label'      => 'My Referral Link',
                      'route'      => 'friendsinviter_reflink',
                      'action'     => 'reflink',
                      'controller' => 'index',
                      'module'     => 'friendsinviter'
                     ),
                );
    
    return $links;
    
  }
  
  public function setupNavigation() {

    $links = $this->getNavigation();

    $this->view->navigation = new Zend_Navigation();
    $this->view->navigation->addPages($links);

    
  }
















  public function inviteresendAction()
  {

    $viewer = Engine_Api::_()->user()->getViewer();
    if( !$viewer->getIdentity() ) {
      $this->view->status = false;
      $this->view->error = true;
      $this->view->message = 'AUTH_FAIL';
      return;
    }


    $settings = Engine_Api::_()->getApi('settings', 'core');
    $api = Engine_Api::_()->getApi('core', 'friendsinviter');

    $inviteid = intval($this->_getParam('id'));

    $table = Engine_Api::_()->getDbtable('invites', 'invite');
    $select = $table->select()
          ->where('id = ?', $inviteid)
          ->where('user_id = ?', $viewer->getIdentity());
          
    $invite_data = $table->fetchRow($select);
    
    if(empty($invite_data)) {
      return;
    }
    

    if($settings->getSetting('user.signup.inviteonly') == 0) {
      $api->fi_send_invitation($viewer, $invite_data->recipient, $invite_data->message, true);
    } else {
      $api->fi_send_invitecode($viewer, $invite_data->recipient, $invite_data->message, true);
    }
    
  }
  
  
  public function invitedeleteAction()
  {

    $table = Engine_Api::_()->getDbtable('invites', 'invite');

    // Check viewer
    $viewer = Engine_Api::_()->user()->getViewer();
    if( !$viewer->getIdentity() ) {
      $this->view->status = false;
      $this->view->error = true;
      $this->view->message = 'AUTH_FAIL';
      return;
    }

    $id = $this->_getParam('id');
    
    $table = Engine_Api::_()->getDbtable('invites', 'invite');
    $table->delete(array(
      'id = ?' => $id,
      'user_id = ?' => $viewer->getIdentity()
    ));
    
  }
  

  public function findfriendsAction()
  {

    // Check viewer
    $viewer = Engine_Api::_()->user()->getViewer();

    if( !$viewer->getIdentity() ) {
      
      // if this is done via signup - save
      $session = new Zend_Session_Namespace('Friendsinviter_Plugin_Signup_Invite');
      $session->friendsinviter_befriend = $this->_getParam('befriend');
      
      $this->view->status = false;
      $this->view->error = true;
      $this->view->message = 'AUTH_FAIL';
      return;
    }
    
    $befriend = $this->_getParam('befriend');
    $friendships_count = Engine_Api::_()->getApi('core', 'friendsinviter')->fi_befriend_contacts( $befriend );

    
    echo  $friendships_count;
    
  }


  public function hideteaserAction() {
    
    $viewer = Engine_Api::_()->user()->getViewer();

    $table  = Engine_Api::_()->getDbTable('teasersettings', 'friendsinviter')->setEnabled($viewer, 0);
    
  }




  public function getcontactsAction() {

    $response = array('status'    => 0,
                     );


    $fi_username = $this->_getParam('fi_username','');
    $fi_password = $this->_getParam('fi_password','');
  
    $fi_domain = $this->_getParam('fi_domain','');
    $fi_typed_domain = $this->_getParam('fi_domain_type','');
    $fi_provider = $this->_getParam('fi_provider', 'auto');
  
    $fi_find_friends = (int) $this->_getParam('fi_find_friends', 0);
    $fi_captcha_response = $this->_getParam('fi_captcha_response');
    $fi_session = $this->_getParam('fi_session');

    $fi_captcha_required = false;
    $fi_social_contacts = null;
    $fi_session = '';
    $fi_importing = false;
    $fi_contacts = null;
    $fi_friends = null;
    $fi_found_friends = 0;
    $fi_unfound_friends = 0;
  
    if(empty($fi_session)) {
      $fi_session = null;
    }
  
    if(empty($fi_captcha_response)) {
      $fi_captcha_response = null;
    }
    
    $client = $_SERVER['REMOTE_ADDR'];
    
    $api = Engine_Api::_()->getApi('core', 'friendsinviter');
    $viewer = Engine_Api::_()->user()->getViewer();
    
    $fi_import_result = $api->fi_import_contacts($fi_username, $fi_password, $fi_domain, $fi_typed_domain, $fi_provider, $fi_find_friends, $viewer, $fi_session, $fi_captcha_response, $client);
  
    $is_error = 0;
    $error_message = '';
  
    $fi_captcha_required = false;
    $fi_captcha_url = '';
    
    if(isset($fi_import_result['error_code']) || isset($fi_import_result['error_message'])) {
  
      if(isset($fi_import_result['captcha_url'])) {
        $fi_captcha_url = $fi_import_result['captcha_url'];
        $fi_captcha_required = true;
        $fi_session = $fi_import_result['session'];
      }
  
      $is_error = 1;
      $error_message = $fi_import_result['error_message'];
  
    } else {
  
      $fi_importing = true;
      $fi_contacts = $fi_import_result['contacts'];
      $fi_unfound_friends = count($fi_contacts);
      $fi_friends = isset($fi_import_result['friends']) ? $fi_import_result['friends'] : array();
      $fi_found_friends = count($fi_friends);
      $fi_social_contacts = isset($fi_import_result['social_contacts']) ? $fi_import_result['social_contacts'] : array();
      $fi_session = $fi_import_result['session'];
  
      }
  
    $response['captcha_required'] = $fi_captcha_required;
    $response['social_contacts'] = $fi_social_contacts;
    $response['session'] = $fi_session;
    $response['importing'] = $fi_importing;
    $response['contacts'] = $fi_contacts;
    $response['friends'] = $fi_friends;
    $response['found_friends'] = $fi_found_friends;
    $response['unfound_friends'] = $fi_unfound_friends;
  
    $response['status'] = $is_error;
    $response['err_msg'] = Zend_Registry::get('Zend_Translate')->_($error_message);
    $response['captcha_required'] = $fi_captcha_required;
    $response['captcha_url'] = $fi_captcha_url;
    
    foreach($response as $key => $val) {
      $this->view->$key = $val;
    }
    
  }


  public function notifyerrorAction()
  {
    
    $viewer = Engine_Api::_()->user()->getViewer();

    //$settings = Engine_Api::_()->getApi('settings', 'core');
    $api = Engine_Api::_()->getApi('core', 'friendsinviter');

    $error = $this->_getParam('error','');
    
    $api->notifyError($viewer, $error);
    
  }
  
  public function oauthgmailAction() {

    $code = $this->_getParam('code');
    
    $settings = Engine_Api::_()->getApi('settings', 'core');
    
    $client_id = $settings->getSetting('friendsinviter.oauth_gmail_client_id','');
    $client_secret = $settings->getSetting('friendsinviter.oauth_gmail_client_secret','');

    $redirect_uri = ( _ENGINE_SSL ? 'https://' : 'http://' )
                    . $_SERVER['HTTP_HOST']
                    . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
                          'module'      => 'friendsinviter',
                          'controller'  => 'index',
                          'action'      => 'oauthgmail',
                          ), 'default', true);

    if(!empty($code)) {
      
      $params = array('code'          => $code,
                      'client_id'     => $client_id,
                      'client_secret' => $client_secret,
                      'redirect_uri'  => $redirect_uri,
                      'grant_type'    => 'authorization_code'
                      );

      
      $post = http_build_query( $params,
                                null, '&' );
      
      $ch = curl_init("https://accounts.google.com/o/oauth2/token");
      
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
      
      $response = curl_exec($ch);
      
      if(curl_errno($ch)) {
        $error = "Gmail OAuth Network error - " . curl_error($ch);
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
      }
      
      $r = json_decode($response);
      
      $access_token = $r->access_token;
    
      curl_setopt($ch, CURLOPT_HTTPGET, 1);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('GData-Version: 3.0', 'Authorization: Bearer ' . $access_token) );
      
      $url = "https://www.google.com/m8/feeds/contacts/default/full" . "?max-results=10000&access_token=" . $access_token;
      
      curl_setopt($ch, CURLOPT_URL, $url);
    
      $response = curl_exec($ch);
      if(curl_errno($ch)) {
        $error = "Gmail OAuth Network error - " . curl_error($ch);
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
      }
      
      //Zend_Loader::loadClass('Zend_Gdata_App');
      $app = new Zend_Gdata_App();
      
      try {
        $feed = $app->importString($response, 'Zend_Gdata_Feed');
      } catch(Zend_Gdata_App_Exception $ex) {

        $error = "Gmail OAuth Content error - " . $ex->getMessage();
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
        
      }
      
      $contacts = array();
      
      foreach($feed as $entry) {
        
        $name = $entry->title->text;
        $email = null;
        
        $extensions = $entry->getExtensionElements();
      
        foreach ($extensions as $extension) {
          if ($extension->rootElement == 'email') {
            $attributes = $extension->getExtensionAttributes();
            $email = $attributes['address']['value'];
          }
        }
        if ($email) {
          $contacts[] = array('name' => $name, 'email' => $email);
        }  
      }
      
      
      $apiresponse = array();
      
      foreach($contacts as $contact) {
        $apiresponse[] = implode('|||', array('0', $contact['name'], $contact['email'], 'photo'));
      }
      $apiresponse = implode('$$$', $apiresponse);
      
      echo <<<EOC
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="en-US" />
<script>
window.opener.fi_popup_success = true;
window.opener.fi_newMessage("$apiresponse");
self.close();
</script>
</head>
<body>
</body>
</html>
EOC;
      
      exit;
      
      
      
    } else {

      $url = 'https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri=' . $redirect_uri . '&response_type=code&client_id=' . $client_id;
      header("Location: $url");
      exit;
      
    }
    
  }
  
  
  public function oauthyahooAction() {

    require_once dirname(__FILE__) . '/../lib/Yahoo.inc';
    
    $settings = Engine_Api::_()->getApi('settings', 'core');
    
    $start = $this->_getParam('start',0);
    
    //$oauth_domain = $settings->getSetting('friendsinviter.oauth_yahoo_domain','');
    
    $oauth_consumer_key = $settings->getSetting('friendsinviter.oauth_yahoo_consumer_key','');
    $oauth_consumer_secret = $settings->getSetting('friendsinviter.oauth_yahoo_consumer_secret','');
    $oauth_app_id = $settings->getSetting('friendsinviter.oauth_yahoo_app_id','');
    
    YahooLogger::setDebug(false);

    if($start == 1) {
      YahooSession::clearSession();
    }   

    $hasSession = YahooSession::hasSession($oauth_consumer_key, $oauth_consumer_secret, $oauth_app_id);

    if($hasSession == FALSE) {
    
      //$callback = YahooUtil::current_url();
      
      $callback = ( _ENGINE_SSL ? 'https://' : 'http://' )
                      . $_SERVER['HTTP_HOST']
                      . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
                            'module'      => 'friendsinviter',
                            'controller'  => 'index',
                            'action'      => 'oauthyahoo',
                            ), 'default', true);
                      
      $auth_url = YahooSession::createAuthorizationUrl($oauth_consumer_key, $oauth_consumer_secret, $callback);
    
      header("Location: $auth_url");
      exit;
    
    }
    
    $session = YahooSession::requireSession($oauth_consumer_key, $oauth_consumer_secret, $oauth_app_id);
    
    if(!$session) {

        $error = "Yahoo OAuth Session error";
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
        
    }
      

    $user = $session->getSessionedUser();
    
    $ycontacts = $user->getContacts(0, 100000);
    
    $contacts = array();
    
    if(is_object($ycontacts)) {
    foreach($ycontacts->contacts->contact as $contact) {
      $name = null;
      $email = null;
      foreach($contact->fields as $field) {
        if($field->type == 'email') {
          $email = $field->value;
        }
        if($field->type == 'name') {
          $name = $field->value->givenName;
          if($field->value->middleName != '') {
            $name .= ' ' . $field->value->middleName;
          }
          if($field->value->familyName != '') {
            $name .= ' ' . $field->value->familyName;
          }
        }
      }
      if($email != "") {
        $contacts[] = array('name'  => $name, 'email' => $email);
      }
    }
    }
    


    $apiresponse = array();
    
    foreach($contacts as $contact) {
      $apiresponse[] = implode('|||', array('0', $contact['name'], $contact['email'], 'photo'));
    }
    $apiresponse = implode('$$$', $apiresponse);
    
    echo <<<EOC
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="en-US" />
<script>
window.opener.fi_popup_success = true;
window.opener.fi_newMessage("$apiresponse");
self.close();
</script>
</head>
<body>
</body>
</html>
EOC;
    
    exit;
    
  }
  


  public function oauthliveAction() {
    
    $code = $this->_getParam('code');
    
    $settings = Engine_Api::_()->getApi('settings', 'core');
    
    $client_id = $settings->getSetting('friendsinviter.oauth_live_client_id','');
    $client_secret = $settings->getSetting('friendsinviter.oauth_live_client_secret','');

    $redirect_uri = ( _ENGINE_SSL ? 'https://' : 'http://' )
                    . $_SERVER['HTTP_HOST']
                    . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
                          'module'      => 'friendsinviter',
                          'controller'  => 'index',
                          'action'      => 'oauthlive',
                          ), 'default', true);

    if(!empty($code)) {
      
      $params = array('code'          => $code,
                      'client_id'     => $client_id,
                      'client_secret' => $client_secret,
                      'redirect_uri'  => $redirect_uri,
                      'grant_type'    => 'authorization_code'
                      );

      
      $post = http_build_query( $params,
                                null, '&' );
      
      $ch = curl_init("https://login.live.com/oauth20_token.srf");
      
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
      
      $response = curl_exec($ch);
      
      if(curl_errno($ch)) {
        $error = "Live OAuth Network error - " . curl_error($ch);
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
      }
      
      $r = json_decode($response);
      
      $access_token = $r->access_token;
    
      $url = 'https://apis.live.net/v5.0/me/contacts?access_token=' . $access_token;

      curl_setopt($ch, CURLOPT_HTTPGET, 1);
      curl_setopt($ch, CURLOPT_URL, $url);
    
      $response = curl_exec($ch);
      if(curl_errno($ch)) {
        $error = "Live OAuth Network error - " . curl_error($ch);
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
      }
      
      $data = json_decode($response);

      if($data == null)  {

        $error = "Live OAuth Content error - " . $ex->getMessage();
        
      echo <<<EOC
<script>
window.opener.fi_errorOccured("$error",0);
self.close();
</script>
EOC;
      exit;
        
      }
      
      $contacts = array();
      
      foreach($data->data as $entry) {
        
        $name = $entry->name;
        $email = $entry->emails->preferred;
        
        if ($email) {
          $contacts[] = array('name' => $name, 'email' => $email);
        }  
      }
      
      $apiresponse = array();
      
      foreach($contacts as $contact) {
        $apiresponse[] = implode('|||', array('0', $contact['name'], $contact['email'], 'photo'));
      }
      $apiresponse = implode('$$$', $apiresponse);
      
      echo <<<EOC
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="en-US" />
<script>
window.opener.fi_popup_success = true;
window.opener.fi_newMessage("$apiresponse");
self.close();
</script>
</head>
<body>
</body>
</html>
EOC;
      
      exit;
      
      
      
    } else {

      $url = 'https://login.live.com/oauth20_authorize.srf?client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&scope=wl.basic,wl.contacts_emails&response_type=code';
      header("Location: $url");
      exit;
      
    }
    
  }
  
}
